import datetime
from flask import Blueprint,request,jsonify
import requests

from views.db import db

import json


bp_message = Blueprint("message",__name__)


def post_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_message.route('/userlist')
def userlist():
    sql = "select d.name,u.username,u.id,u.password,u.status from user as u left join dept as d on u.dept_id=d.id"
    res = db.get_all(sql)
 
           
    return jsonify({'code': 200, 'list': res})


@bp_message.route('/post_Message', methods=['POST','GET'])
def post_Message():
    


    if request.method=='GET':
        userid = request.args.get("userid")
        sql1 = "select username from user where id=%d"%(int(userid))
        res1 = db.get_one(sql1)
        sql = "select * from message"
        res = db.get_all(sql)
        for i in res:
            i['username'] = res1['username']
        return jsonify({'code': 200, 'list': res})
    else:
        data = post_data()
        userlist1 = json.dumps(data['userlist'])
        try:
            if len(data['userlist']) > 0:
                sql = "insert into message(title,content,status,designate,type,stime,etime,priority,userlist) values('%s','%s',1,%d,%d,'%s','%s',%d,'%s')" % (
                    data['title'], data['content'], int(data['designate']), int(data['type']), data['stime'],
                    data['etime'],int(data['priority']), userlist1)
            else:
                sql = "insert into message(title,content,status,designate,type,stime,etime,priority) values('%s','%s',1,%d,%d,'%s','%s',%d)" % (
                    data['title'], data['content'], int(data['designate']), int(data['type']), data['stime'],
                    data['etime'],
                    int(data['priority']))
            db.add(sql)
            db.commit()
            return jsonify({'code': 200, 'msg': '添加成功'})
        except:
            db.rollback()
            return jsonify({'code': 10010, 'msg': '添加失败'})

